from Tkinter import *
import Tkinter
import tkMessageBox

import jarvars
from save import saveConfiguration

class editUsers(Frame):

    def __init__(self, master=None):
        
        
        users = jarvars.AuthorizedAimUsers        
            
        self.win = Toplevel(master)
        self.win.geometry("%dx%d%+d%+d" % (400, 100, 150, 0))
        Frame.__init__(self,self.win)
        self.user = StringVar()

        self.grid(padx=2, pady=2,sticky=N+S+E+W)


        self.userLabel = Label(self, text="User")
        self.userToAdd = Entry(self, width=15)
        self.userToAddLabel = Label(self, text="User to add")
        self.addButton = Button(self, text="Add", command=self.addUser)
        self.removeButton = Button(self, text="Remove Selected", command=self.removeUser)
        if len(users) > 0:
            self.users = OptionMenu(self, self.user, *users)
            self.user.set(jarvars.AuthorizedAimUsers[0])
        else:
            self.users = Label(self, text="No Current Users")

        self.userLabel.grid(row=0, column=0, sticky=E)
        self.users.grid(row=0,column=1, sticky=W)
        self.removeButton.grid(row=0, column=2, sticky=W)
        self.userToAddLabel.grid(row=1, column=0, sticky = E)
        self.userToAdd.grid(row=1, column=1, sticky=W)
        self.addButton.grid(row=1,column=2, sticky=W)
        self.bind("<Destroy>", self._destroy)
        self.master.title("Edit Users")
        
       
    def addUser(self):
        
        user = self.userToAdd.get()
        if len(user) == 0:
            return
        print "Add User", user
        jarvars.AuthorizedAimUsers.append(user)
        if len(jarvars.AuthorizedAimUsers) == 1:
            print "Switch stuff"
            self.users.grid_forget()
            self.users = OptionMenu(self, self.user, *jarvars.AuthorizedAimUsers)        
            self.users.grid(row=0,column=1, sticky=W)
            self.user.set(user)
        else:
            menu = self.users["menu"]
            menu.insert('end', 'command', label=user, command=Tkinter._setit(self.user, user, None))
        self.userToAdd.delete(0,END)
        

    def removeUser(self):
        user = self.user.get()
        print "Remove User", user
        jarvars.AuthorizedAimUsers.remove(user)
        if len(jarvars.AuthorizedAimUsers)== 0:
            self.users.grid_forget()
            self.users = Label(self, text="No Users")
            self.users.grid(row=0, column=1, sticky=W)
        else:
            self.user.set(jarvars.AuthorizedAimUsers[0])
        menu = self.users["menu"]
        menu.delete(user)

                
    def _destroy(self, Event=None):
        saveConfiguration()
        self.win.destroy()
    
if __name__ == "__main__":
    print "Not a main module"
    root = Tk()
    eu = editUsers(root)
    while(1):
        eu.update()
    
    


